<template>
  <el-row>
    <el-col :sm="12" :lg="6" v-for="(item, index) in thirdAuth">
      <div style="text-align: center">
        <div>
          <img :src="item.icon" style="width: 100px;border-radius: 5px" alt=""/>
        </div>
        <div style="margin-top: 15px">
          <el-link v-if="!item.hasBind" type="primary" @click="handleAuth(item)">授权{{ item.title }}登录</el-link>
          <el-link v-else type="danger" @click="handleCancelAuth(item)">解绑{{ item.title }}授权</el-link>
        </div>
      </div>
    </el-col>

    <el-divider/>
    <el-col :sm="24" style="text-align: center">
      <el-button type="danger" @click="close">关闭</el-button>
    </el-col>
  </el-row>

</template>

<script setup>

import {bindThirdAuth, getThirdAuthList, unbindThirdAuth} from "@/api/auth.js";
import {activeTab} from "@/api/system/user";

const {proxy} = getCurrentInstance();
const thirdAuth = ref([])

onMounted(async () => {
  const code = new URLSearchParams(window.location.search).get("code");
  const state = new URLSearchParams(window.location.search).get("state");
  const thirdLoginType = new URLSearchParams(window.location.search).get("type");
  const error_description = new URLSearchParams(window.location.search).get("error_description");
  if (code === null && thirdLoginType !== null) {
    proxy.$message.error(error_description)
  }
  if (code === null) {
    return;
  }
  activeTab.value = "thirdAuth"
  // 调用后端API，用code换取第三方应用的accessToken，获取用户信息 完成绑定操作
  bindThirdAuth(code, thirdLoginType, state).then(res => {
    proxy.$message.success("绑定成功")
    initThirdAuthList()
  })
})

function initThirdAuthList() {
  getThirdAuthList().then(res => {
    console.log(res.data)
    thirdAuth.value = res.data
  })
}

function handleAuth(item) {
  window.location.href = item.authUrl;
}

function handleCancelAuth(item) {
  proxy.$modal.confirm('是否确认解绑"' + item.title + '"的授权?').then(function () {
    return unbindThirdAuth(item.title);
  }).then(() => {
    initThirdAuthList();
    proxy.$modal.msgSuccess("解绑成功");
  }).catch(() => {});
}

/** 关闭按钮 */
function close() {
  proxy.$tab.closePage();
}

initThirdAuthList();
</script>
